<!doctype html>
<!--
Copyright 2018 The Immersive Web Community Group

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<html>
  <head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=no'>
    <meta name='mobile-web-app-capable' content='yes'>
    <meta name='apple-mobile-web-app-capable' content='yes'>
    <link rel='icon' type='image/png' sizes='32x32' href='../favicon-32x32.png'>
    <link rel='icon' type='image/png' sizes='96x96' href='../favicon-96x96.png'>
    <link rel="manifest" href="../manifest.json">
    <link rel='stylesheet' href='../css/common.css'>

    <title>User Agent Prompts</title>
  </head>
  <body>
    <header>
      <details open>
        <summary>User Agent Prompts</summary>
        <p>
          Tests requesting various prompts (PWA install, permission requests, notifications) from within XR.
          Demonstrates how the UA handles those prompts, if at all.
          <a class="back" href="./">Back</a>
        </p>
      </details>
    </header>
    <script type="module">
      import {WebXRSampleApp} from '../js/webxr-sample-app.js';
      import {UrlTexture} from '../js/render/core/texture.js';
      import {ButtonNode} from '../js/render/nodes/button.js';
      import {Gltf2Node} from '../js/render/nodes/gltf2.js';
      import {mat4} from '../js/render/math/gl-matrix.js';
      import {QueryArgs} from '../js/util/query-args.js';

      // If requested, use the polyfill to provide support for mobile devices
      // and devices which only support WebVR.
      import WebXRPolyfill from '../js/third-party/webxr-polyfill/build/webxr-polyfill.module.js';
      if (QueryArgs.getBool('usePolyfill', true)) {
        let polyfill = new WebXRPolyfill();
      }

      let serviceWorkerRegistration;

      if ('serviceWorker' in navigator) {
        window.addEventListener('load', async () => {
          try {
            const registration = await navigator.serviceWorker.register('../service-worker.js');
            console.log('Service worker registered successfully', registration);
            serviceWorkerRegistration = registration;
          } catch (error) {
            console.error('Something went wrong while registering service worker', error);
          }
        });
      }

      const title = 'Notification title';

      const options = {
        body: `This notification can have a maximum of ${window.Notification?.maxActions || 0} action button(s). Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.`,
        data: {
          url: 'https://google.com',
        },
        image: '../media/manifest/screenshot-4.png',
        icon: '../media/manifest/icon-192x192-regular.png',
        badge: '../media/manifest/icon-192x192-regular.png',
        requireInteraction: false,
        actions: [
          {
            action: 'reply',
            type: 'text',
            title: 'One (Reply)',
            icon: '../media/manifest/icon-192x192-regular.png',
            placeholder: 'Reply placeholder',
          },
          {
            action: 'two',
            type: 'button',
            title: 'Two',
            icon: '../media/manifest/icon-192x192-regular.png',
          },
          {
            action: 'three',
            type: 'button',
            title: 'Three',
            icon: '../media/manifest/icon-192x192-regular.png',
          },
          {
            action: 'four',
            type: 'button',
            title: 'Four',
            icon: '../media/manifest/icon-192x192-regular.png',
          },
          {
            action: 'five',
            type: 'button',
            title: 'Five',
            icon: '../media/manifest/icon-192x192-regular.png',
          },
        ],
      };

      const showNotification = () => serviceWorkerRegistration?.showNotification?.(title, options);

      let deferredInstallEvent;

      window.addEventListener('beforeinstallprompt', (event) => {
        event.preventDefault();
        deferredInstallEvent = event;
        addPermissionButton('../media/textures/install-pwa-button.png', installPWA, 0, 1.54);
      });

      const installPWA = async (success, _) => {
        const { outcome } = await deferredInstallEvent?.prompt();
        if (outcome === 'accepted') {
          success();
        }
        // If PWA install prompt is dismissed, closed or ignored, it can be requested again.
      };

      const BUTTON_PER_ROW = 5;
      const BUTTON_ROW_ARC = Math.PI * 0.2;
      const BUTTON_ROW_HEIGHT = 0.12;
      const BUTTON_GRID_HEIGHT = 1.3;
      const BUTTON_GRID_DISTANCE = 1.0;

      // WebXR sample app setup
      let app = new WebXRSampleApp({
        referenceSpace: 'local-floor'
      });
      document.querySelector('header').appendChild(app.xrButton.domElement);

      app.scene.addNode(new Gltf2Node({url: '../media/gltf/cube-room/cube-room.gltf'}));

      let checkTexture = new UrlTexture('../media/textures/check-button.png');
      let xTexture = new UrlTexture('../media/textures/x-button.png');
      function addPermissionButton(iconUrl, callback, yAngle, yOffset) {
        let button = new ButtonNode(new UrlTexture(iconUrl), () => {
          callback(
            () => { button.iconTexture = checkTexture; }, // Success callback
            () => { button.iconTexture = xTexture; } // Failure callback
          )
        });
        mat4.identity(button.matrix);
        mat4.translate(button.matrix, button.matrix, [0, yOffset, 0]);
        mat4.rotateY(button.matrix, button.matrix, yAngle);
        mat4.translate(button.matrix, button.matrix, [0, 0, -BUTTON_GRID_DISTANCE]);
        app.scene.addNode(button);
      }

      // Builds a cylindrical grid of buttons
      function addPermissionButtons(buttonList) {
        let count = buttonList.length;
        let rows = Math.ceil(count / BUTTON_PER_ROW);
        let firstRowOffset = (rows / 2) * BUTTON_ROW_HEIGHT;
        let anglePerButton = BUTTON_ROW_ARC / BUTTON_PER_ROW;
        let rowAngleOffset = (BUTTON_ROW_ARC * 0.5) - (anglePerButton * 0.5)

        for (let i = 0; i < count; ++i) {
          let button = buttonList[i];
          let yAngle = rowAngleOffset - ((i % BUTTON_PER_ROW) * anglePerButton);
          let row = Math.floor(i / BUTTON_PER_ROW);
          let yOffset = BUTTON_GRID_HEIGHT + (firstRowOffset - (row * BUTTON_ROW_HEIGHT));
          addPermissionButton(button.icon, button.callback, yAngle, yOffset);
        }
      }

      addPermissionButtons([
        {
          icon: '../media/textures/microphone-button.png',
          callback: (success, fail) => {
            navigator.mediaDevices?.getUserMedia?.({ audio: true })
            .then(success, fail);
          }
        },
        {
          icon: '../media/textures/camera-button.png',
          callback: (success, fail) => {
            navigator.mediaDevices?.getUserMedia?.({ video: true })
            .then(success, fail);
          }
        },
        {
          icon: '../media/textures/screenshare-button.png',
          callback: (success, fail) => {
            navigator.mediaDevices?.getDisplayMedia?.()
            .then(success, fail);
          }
        },
        {
          icon: '../media/textures/location-button.png',
          callback: (success, fail) => {
            navigator.geolocation?.getCurrentPosition?.(success, fail);
          }
        },
        {
          icon: '../media/textures/notifications-button.png',
          callback: (success, fail) => {
            window.Notification?.requestPermission?.(outcome => {
              switch(outcome) {
                case 'granted':
                  success();
                  addPermissionButton('../media/textures/show-notification-button.png', showNotification, 0, 1.18);
                  break;
                case 'denied':
                  fail();
                  break;
                case 'default':
                  // If permission prompt is closed or ignored,
                  // the outcome value is `default`, and permission can be requested again.
                  // https://notifications.spec.whatwg.org/#permission-model
                  break;
              }
            })
          }
        },
        {
          icon: '../media/textures/bluetooth-button.png',
          callback: (success, fail) => {
            navigator.bluetooth?.requestDevice?.({
              // filters: [...] <- Prefer filters to save energy & show relevant devices.
              // acceptAllDevices here ensures dialog can populate, we don't care with what.
              acceptAllDevices: true
            })
            .then(device => device.gatt.connect())
            .then(success, fail);
          }
        },
        {
          icon: '../media/textures/usb-button.png',
          callback: (success, fail) => {
            navigator.usb?.requestDevice?.({ filters: [{}] })
            .then(success, fail);
          }
        },
        {
          icon: '../media/textures/hid-button.png',
          callback: (success, fail) => {
            navigator.hid?.requestDevice?.({ filters: [] })
            .then(devices => { devices.length > 0 ? success() : fail() });
          }
        },
        {
          icon: '../media/textures/midi-button.png',
          callback: (success, fail) => {
            navigator.requestMIDIAccess?.({ sysex: true })
            .then(success, fail);
          }
        },
        {
          icon: '../media/textures/serial-button.png',
          callback: (success, fail) => {
            navigator.serial?.requestPort?.({ filters: [] })
            .then(success, fail);
          }
        },
      ]);

      // Start the XR application.
      app.run();
    </script>
  </body>
</html>
